# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
import codecs
from scrapy.pipelines.images import ImagesPipeline

from scrapy.exporters import JsonItemExporter

class JsonExporterPipeline(object):
    def __init__(self):
        self.file=open('articleexport.json','wb')
        self.exporter=JsonItemExporter(self.file,encoding='utf-8',ensure_ascii=False)
        self.exporter.start_exporting()
    def close_spider(self,spider):
        self.exporter.finish_exporting()
        self.close_spider()

    def process_item(self,item,spider):
        self.exporter.export_item(item)
        return item

class ArticlespiderPipeline(object):
    def process_item(self, item, spider):
        return item

class ArticleImagePipeline(ImagesPipeline):
    def item_completed(self, results, item, info):
        for ok,value in results:
            image_file_path=value("path")
        item["image_path"]=image_file_path

        return item


class Jsonpipeline(object):
    def __init__(self):
        self.file=codecs.open('article.json','w',encoding='utf-8')

    def process_item(self,item,spider):
        lines=json.dumps(dict(item),ensure_ascii=False)+'\n'
        self.file.write(lines)
        return item

    def spider_closed(self,spider):
        self.file.close()


class ArticleImagePipeline(ImagesPipeline):
    def item_completed(self, results, item, info):
        for ok,value in results:
            image_path=value["path"]
        item["image_path"]=image_path

        return item